/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.demo.scheduler.service.communication;

import cn.hutool.core.util.StrUtil;
import info.peigen.hotpot.demo.scheduler.domain.Task;
import info.peigen.hotpot.demo.scheduler.service.step.base.TaskContext;
import info.peigen.hotpot.demo.scheduler.service.task.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.Solon;
import org.noear.solon.annotation.Component;

import java.util.List;
import java.util.function.Consumer;

/**
 * <b>(MqttMock)</b>
 *
 * @author Lihai
 * @version 1.0.0
 * @since 2023/9/8
 */
@Slf4j
@Component
public class MqttMock {
    public void receiveMessage(MqttMessage mqttMessage, Consumer<TaskContext> handle) {
        log.info("收到mqtt推送消息: robotId:{}, requestNo:{}, msg:{}", mqttMessage.getRobotId(), mqttMessage.getRequestNo(), mqttMessage.message);


        TaskService taskService = Solon.context().getBean(TaskService.class);

        List<String> split  = StrUtil.split(mqttMessage.requestNo, "-");
        String       taskId = split.get(0);
        Task         task   = taskService.getTaskIdMap().get(taskId);
        if (task == null || !task.getSendRequestNo().contains(mqttMessage.requestNo)) {
            System.err.println("没有下达过的指令");
            return;
        }
        TaskContext taskContext = TaskContext.builder()
                .task(task)
                .callBackResult(CallBackResult.builder().message(mqttMessage.message).requestNo(mqttMessage.getRequestNo()).success(true).referMachineId(mqttMessage.robotId).taskId(mqttMessage.getRobotId()).build())
                .build();
        handle.accept(taskContext);
    }

}
